<?php
namespace YDCMS\controllers;

use YDCMS\core\Controller;
use YDCMS\models\User;

class AdminController extends Controller
{
    private $user;

    public function __construct()
    {
        $this->user = new User();
    }

    public function login()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $username = $_POST['username'] ?? '';
            $password = $_POST['password'] ?? '';
            $captcha_selection = $_POST['captcha_selection'] ?? '';

            // 验证图片验证码（data-type=ship 的索引为 0,2,4）
            $correct = ['0', '2', '4'];
            $selected = array_filter(explode(',', $captcha_selection), 'strlen');
            sort($selected);
            if ($selected !== $correct) {
                echo $this->view('admin/login', [
                    'error' => '验证码错误，请正确选择所有包含货轮的图片'
                ]);
                return;
            }

            $user = $this->user->findByUsername($username);
            if (!$user) {
                echo $this->view('admin/login', [
                    'error' => '用户名不存在，调试：' . htmlspecialchars($username)
                ]);
                return;
            }

            if (!$this->user->verifyPassword($password, $user['password'])) {
                echo $this->view('admin/login', [
                    'error' => '密码错误，调试：输入密码 ' . htmlspecialchars($password) . ' 数据库密码 ' . htmlspecialchars($user['password'])
                ]);
                return;
            }

            if (!$this->user->hasRole($user['id'], 'admin')) {
                echo $this->view('admin/login', [
                    'error' => '无管理员权限，调试：用户ID ' . $user['id']
                ]);
                return;
            }

            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_role'] = 'admin';
            $_SESSION['username'] = $user['username'];
            return $this->redirect('/admin/dashboard');
        }
        echo $this->view('admin/login');
    }

    public function dashboard()
    {
        // 检查是否已登录
        if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
            return $this->redirect('/admin/login');
        }

        echo $this->view('admin/dashboard', [
            'username' => $_SESSION['username']
        ]);
    }

    public function logout()
    {
        session_destroy();
        return $this->redirect('/admin/login');
    }
} 